
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:kmxy_base/base/base_global.dart';
import 'package:kmxy_base/entity/screen_default.dart';
import 'package:kmxy_base/util/event.dart';
import 'package:kmxy_base/util/permission/permission_util.dart';

final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();

abstract class MainBase extends StatelessWidget with WidgetsBindingObserver {
  const MainBase({super.key});

  get clipboardDataText => null;

  @override
  Widget build(BuildContext context) {
    ScreenDefault screenDefault = setDefaultWH();
    WidgetsBinding.instance.addObserver(this);
    if (!BaseGlobal.isMainInitData) {
      BaseGlobal.isMainInitData = true;
      initData();
    }
    initBuild();
    return ScreenUtilInit(
      designSize: Size(screenDefault.width, screenDefault.height),
      builder: (BuildContext context, Widget? widget) => MaterialApp(
        navigatorKey: navigatorKey,
        localizationsDelegates: localizationsDelegates(),
        supportedLocales: const [
          Locale('zh', 'CN'),
          Locale('en', 'US'),
        ],
        title: setTitle(),
        //注册路由表
        initialRoute: '/',
        routes: {
          '/': (context) => setStartPage(context),
        },
        builder: (BuildContext context, Widget? child) {
          /// make sure that loading can be displayed in front of all other widgets
          Widget page = setPageContent(context, child);
          return FlutterEasyLoading(
            child: MediaQuery(
              ///设置文字大小不随系统设置改变
              data: MediaQuery.of(context).copyWith(textScaleFactor: 1.0),
              child: page,
            ),
          );
        },
      ),
    );
  }

  /// 设置全局页面，child也要加入到页面中
  Widget setPageContent(BuildContext context, Widget? child) {
    return child ?? Container();
  }

  /// APP启动进入的页面
  Widget setStartPage(BuildContext context);

  /// APP标题
  String setTitle();

  /// 设置UI设计稿尺寸
  ScreenDefault setDefaultWH();

  /// 初始化数据，只会调用一次
  initData();

  /// 初始化数据，会根据页面刷新调用多次
  initBuild() {}

  /// 国际化处理
  Iterable<LocalizationsDelegate<dynamic>> localizationsDelegates();

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    if (state == AppLifecycleState.paused) {
      appBackstage();
    }
    if (state == AppLifecycleState.resumed) {
      appFrontdesk();
    }
  }

  /// APP切换到后台的回调
  void appBackstage() {}

  /// APP切换到前台的回调
  void appFrontdesk() {
    Event.eventBus
        .fire(Event(PermissionUtil.getInstance.EVENT_PATROL_PERMISSION, ''));
    Event.eventBus.fire(Event(PermissionUtil.getInstance.EVENT_PERMISSION, ''));
  }
}
